<template>
	<view class="all">
		<view class="share_all">
			<canvas style="width: 1000px; height: 800px;background-color: #FFFFFF" canvas-id="firstCanvas"></canvas>
		</view>
		<scroll-view scroll-y="true" style="height: 100vh;">
			<view class="head">
				<view class="head_one" v-for="(item,index) of tabList" :key="index" @click="changeTab(index,item.id)">
					<text class="head_one_name" :class="{head_one_name_active:index == tabListIndex}">{{item.name}}</text>
					<text class="head_one_line" :class="{head_one_line_active:index == tabListIndex}"></text>
				</view>
			</view>

			<view class="fill">
				<text class="fill_btn" @click="goTemplate()">快捷填充表单 &nbsp; >></text>
			</view>

			<!-- 必填项 -->
			<view class="info_must">

				<view class="info_must_one">
					<view class="info_must_one_title_input">
						<text class="info_must_one_title">手机号</text>
						<input class="input_phone" placeholder="请填写手机号" placeholder-class="placeholder" type="text" v-model="phone" value="" />
					</view>
					<button class="phone_btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" v-if="phone == ''">获取</button>
				</view>

				<view class="info_must_one">
					<view class="info_must_one_title_input">
						<text class="info_must_one_title">出发地</text>
						<input class="input" placeholder="请填写出发地" placeholder-class="placeholder" type="text" v-model="departurePlace"
						 value="" />
					</view>
				</view>

				<view class="info_must_one">
					<view class="info_must_one_title_input">
						<text class="info_must_one_title">目的地</text>
						<input class="input" placeholder="请填写目的地" placeholder-class="placeholder" type="text" v-model="destination" value="" />
					</view>
				</view>

				<time-selector v-if="startTime != ''" showType="yearToMinute" :beginDate="startTime" endDate="2050-12-31" beginTime="00:00:00"
				 endTime="23:59:59" @btnConfirm="btnConfirm" @btnCancel="btnCancel">
					<view class="info_must_one">
						<view class="info_must_one_title_input">
							<text class="info_must_one_title">时间</text>
							<input class="input" placeholder="请选择出发时间" disabled="true" placeholder-class="placeholder" type="text" v-model="departureTime"
							 value="" />
						</view>
						<image class="more_icon" src="/static/images/more.png" mode=""></image>
					</view>
				</time-selector>


				<view class="info_must_one" @click="openChoosePerson()">
					<view class="info_must_one_title_input">
						<text class="info_must_one_title">{{tabListIndex==0 ? '座位数' : '人数'}}</text>
						<input class="input" :placeholder="tabListIndex==0 ? '请选择座位数' : '请选择人数'" placeholder-class="placeholder" type="number"
						 disabled="true" v-model="personNum" value="" />
					</view>
					<image class="more_icon" src="/static/images/more.png" mode=""></image>
				</view>
			</view>

			<!-- 选填项 -->
			<view class="pass" v-if="tabListIndex == 0">
				<view class="info_must_one">
					<view class="info_must_one_title_input">
						<text class="info_must_one_title">途经</text>
						<input class="input" placeholder="请添加途经 （选填）" placeholder-class="placeholder" type="text" v-model="route" value="" />
					</view>
				</view>
			</view>

			<textarea v-show="!popupStatus" class="textarea" value="" placeholder="请添加备注 （选填）" placeholder-class="placeholder"
			 v-model="ps"></textarea>
			<view :class="['textarea',ps ? '':'placeholder']" v-show="popupStatus">{{ps || '请添加备注 （选填）'}}</view>
			
			<view class="release_btn">
				<text class="btn" @click="releaseBtn">发布</text>
			</view>
		</scroll-view>

		<uni-popup ref="personNum" type="bottom" @change="popupChange">
			<view class="choose_person_num">
				<text class="choose_person_num_one" v-for="(item,index) of personNumList" :key="index" @click="choosePerson(item)">{{item}}</text>
			</view>
		</uni-popup>
		<uni-popup ref="sharepic" type="center" force="force">
			<view class="share_popup">
				<image @click="back_" class="close_icon"  src="/static/images/close.png" mode=""></image>
				<image class="success_icon" src="/static/images/success.png" mode=""></image>
				<text class="share_tip">发布成功，分享行程可 获得更多关注哦！</text>
				<button class="share_btn" style="background-color: #4688FF;color: #FFFFFF;" type="default" open-type="share">分享</button>
			</view>
		</uni-popup>
		
	</view>
</template>

<script>
	import timeSelector from '@/components/wing-time-selector/wing-time-selector.vue';
	import {
		wxUserPhone,
		releaseCarpoolingInfo
	} from '@/Service/login.js';
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	var padDate = function(va) {
		va = va < 10 ? '0' + va : va;
		return va
	};
	export default {
		components: {
			timeSelector,
			uniPopup
		},
		data() {
			return {
				tabList: [],
				tabListIndex: 0,
				tabListId: 0,
				phone: '', //手机号
				departurePlace: '', //出发地
				destination: '', //目的地
				departureTime: '', //出发时间
				personNum: '', //座位数，人数
				personNumList: [1, 2, 3, 4],
				route: '', //途经
				ps: '', //备注
				startTime: '', //选择时间的开始时间

				popupStatus: false, // 人数弹框状态
				pic:null,
				infoId:'',
			}
		},
		onLoad(option) {
			let timestamp = (new Date()).getTime()
			let time = this.formatDate(timestamp)
			this.startTime = time
			this.tabList = JSON.parse(option.typeList)
			this.phone = (uni.getStorageSync("phone") ? uni.getStorageSync("phone") : '');
		},
		onShareAppMessage(res) {
		    return {
				title: '使用恒行通，出行更轻松！',
				path: '/pages/home/index?type=' + this.tabListId + '&carpoolInfoId=' + this.infoId,
				imageUrl:this.pic,
			    success(ret){
					console.log(JSON.stringify(ret))
				    uni.navigateBack({
				    	delta:1
				    })
			    },
			    fail(err){
					console.log(JSON.stringify(err))
				    uni.navigateBack({
				    	delta:1
				    })
			    },
				complete(){
					console.log("123")
					uni.navigateBack({
						delta:1
					})
				}
		    }
		},
		computed: {
			listenTemplate() {
				return this.$store.state.template
			}
		},
		watch: {
			//监听到用户处于未登录状态
			listenTemplate(e) {
				console.log(JSON.stringify(e))
				this.phone = e.phone
				this.departurePlace = e.departurePlace
				this.destination = e.destination
				this.personNum = e.quantity
				this.route = e.pass
				this.ps = e.remark
				
			}
		},
		methods: {
			back_(){
				uni.navigateBack({
					delta:1
				})
			},
			setsharecontent(){
				var ctx = uni.createCanvasContext('firstCanvas',this)
				var titlecolor = '#757575'
				var wordcolor = '#000000'
				var fontSize = 60
				var titlepadding = 40
				var wordleftpadding = 300
				var toppadding = 100
				var toppaddingOne = 30
				
				ctx.setFillStyle('#FFFFFF')
				ctx.fillRect(0, 0, 1000, 800);
				ctx.textAlign = 'left'	// 设置位置
				
				ctx.setFontSize(fontSize);	// 类型
				ctx.setFillStyle(titlecolor)
				ctx.fillText('类型',titlepadding,toppadding + toppaddingOne*4*0);
				ctx.setFontSize(fontSize)
				ctx.setFillStyle(wordcolor)
				ctx.fillText(this.tabList[this.tabListIndex].name,wordleftpadding,toppadding + toppaddingOne*4*0);
				
				ctx.setFontSize(fontSize)	// 时间
				ctx.setFillStyle(titlecolor)
				ctx.fillText('时间',titlepadding,toppadding + toppaddingOne*4*1);
				ctx.setFontSize(fontSize)	
				ctx.setFillStyle(wordcolor)
				ctx.fillText(this.departureTime,wordleftpadding,toppadding + toppaddingOne*4*1);
				
				ctx.setFontSize(fontSize)	// 出发地
				ctx.setFillStyle(titlecolor)
				ctx.fillText('出发地',titlepadding,toppadding + toppaddingOne*4*2);
				ctx.setFontSize(fontSize)
				ctx.setFillStyle(wordcolor)
				ctx.fillText(this.departurePlace,wordleftpadding,toppadding + toppaddingOne*4*2);
				
				ctx.setFontSize(fontSize)// 目的地
				ctx.setFillStyle(titlecolor)
				ctx.fillText('目的地',titlepadding,toppadding + toppaddingOne*4*3);
				ctx.setFontSize(fontSize)	// 字体样式
				ctx.setFillStyle(wordcolor)
				ctx.fillText(this.destination,wordleftpadding,toppadding + toppaddingOne*4*3);
				
				ctx.setFontSize(fontSize)// 人数
				ctx.setFillStyle(titlecolor)
				ctx.fillText('人数',titlepadding,toppadding + toppaddingOne*4*4);
				ctx.setFontSize(fontSize)
				ctx.setFillStyle(wordcolor)
				ctx.fillText(this.personNum,wordleftpadding,toppadding + toppaddingOne*4*4);
				
				ctx.setFontSize(fontSize)// 电话
				ctx.setFillStyle(titlecolor)
				ctx.fillText('电话',titlepadding,toppadding + toppaddingOne*4*5);
				ctx.setFontSize(fontSize)
				ctx.setFillStyle(wordcolor)
				ctx.fillText(this.phone,wordleftpadding,toppadding + toppaddingOne*4*5);
				
				ctx.setFillStyle('#FFFFFF')
				ctx.draw()
				this.$refs.sharepic.open();
				setTimeout(function(){
					uni.hideLoading();
				}, 2000);
				let self = this
				setTimeout(function(){ 
					self.setPic()
				}, 1000);
			},
			setPic(){
				let self = this
				let num = 100
				uni.canvasToTempFilePath({	// 把画布转化成临时文件
					x: 0,
					y: 0,
					destWidth: 1000,
					destHeight: 800,
					fileType: 'jpg',			// 保存成的文件类型
					quality: 1,					// 图片质量
					canvasId: 'firstCanvas',		// 画布ID
					success(res) {
						console.log(JSON.stringify(res))
						self.pic = res.tempFilePath
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			
			// 弹框的change函数
			popupChange(dt) {
				this.popupStatus = dt.show;
			},

			formatDate(val) {
				var value = new Date(val);
				var year = value.getFullYear();
				var month = padDate(value.getMonth() + 1);
				var day = padDate(value.getDate());
				var hour = padDate(value.getHours());
				var minutes = padDate(value.getMinutes());
				var seconds = padDate(value.getSeconds());
				return year + '-' + month + '-' + day;
			},
			//切换tab
			changeTab(index, id) {
				if (this.tabListIndex == index) {
					return
				}
				this.clearData()
				this.tabListIndex = index
				this.tabListId = id
			},
			//时间选择
			btnConfirm(e) {
				var month = e.month
				var day = e.day
				var hour = e.hour
				var minute = e.minute
				if (month < 10) {
					month = '0' + month
				}
				if (day < 10) {
					day = '0' + day
				}
				if (hour < 10) {
					hour = '0' + hour
				}
				if (minute < 10) {
					minute = '0' + minute
				}
				this.departureTime = e.year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + '00'
			},
			btnCancel() {
				console.log('取消时间：');
			},

			//判断用户是否授权手机号
			isHavePhonePower() {
				let self = this
				uni.getSetting({
					success: (res) => {
						console.log(JSON.stringify(res))
						if (res.authSetting['scope.userInfo']) { //用户已授权,
							console.log('已授权')
						} else { //用户还未授权过
							console.log('未授权')
						}
					}
				})
			},

			//获取手机号
			getPhoneNumber(e) {
				let self = this
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					console.log('用户点击允许')
					uni.login({
						provider: "weixin",
						success: (login_ret => {
							console.log('最新的code')
							console.log(login_ret.code)
							let params = {
								code: login_ret.code,
								encryptedData: e.detail.encryptedData,
								iv: e.detail.iv,
							}
							wxUserPhone(params).then((ret) => {
								console.log(JSON.stringify(ret))
								self.phone = ret.data.data
								uni.setStorageSync('phone', ret.data.data)
							}).catch((err) => {
								console.log(err)
							})
						})
					})

				} else {
					console.log('用户点击拒绝')
				}
			},
			//去模板管理
			goTemplate() {
				uni.navigateTo({
					url: '/pages/releasePage/templateManage/templateManage?type=' + this.tabListId
				})
			},

			//打开选择人数
			openChoosePerson() {
				this.$refs.personNum.open();
			},

			//选择人数
			choosePerson(item) {
				console.log(item)
				this.personNum = item
				this.$refs.personNum.close();
			},

			//发布
			releaseBtn() {
				let self = this
				let judge = self.judgeUpData()
				if (!judge) {
					console.log('00000000000')
					return
				}
				uni.showLoading({
					title: '发布中'
				});
				let params = {
					departurePlace: self.departurePlace, //出发地
					departureTime: self.departureTime, //出发时间
					destination: self.destination, //目的地
					type: self.tabListId, //信息类别
					phone: self.phone, //手机号
					quantity: self.personNum, //人数或座位数
					pass: self.route, //途经
					remark: self.ps, //备注
				}
				
				
				releaseCarpoolingInfo(params).then((ret) => {
					console.log(JSON.stringify(ret))
					if (ret.data.code == 0) {
						setTimeout(function() {
							self.infoId = ret.data.data
							self.setsharecontent()
							// self.ToastSuccess('发布成功')
						}, 1000);
						// setTimeout(function() {
						// 	uni.navigateBack({
						// 		delta: 1
						// 	})
						// }, 3000);
					} else {
						uni.hideLoading();
						self.Toast(ret.data.msg)
					}
				}).catch((err) => {
					console.log(err)
				})
			},

			//发布前判断
			judgeUpData() {
				let self = this
				let judge = true
				if (self.phone == '') {
					self.Toast('请填写手机号')
					return false
				}
				if (!(/^1[3456789]\d{9}$/.test(self.phone))) {
					self.Toast('手机号有误')
					return false
				}
				if (self.departurePlace == '') {
					self.Toast('请填写出发地')
					return false
				}
				if (self.destination == '') {
					self.Toast('请填写目的地')
					return false
				}
				if (self.departureTime == '') {
					self.Toast('请选择出发时间')
					return false
				}
				if (self.personNum == '') {
					self.Toast('请填写数量')
					return false
				}

				return judge
			},
			//清空数据
			clearData() {
				this.departurePlace = ''
				this.destination = ''
				this.departureTime = ''
				this.personNum = ''
				this.route = ''
				this.ps = ''
			},
			//普通toast
			Toast(e) {
				uni.showToast({
					title: e,
					icon: 'none',
					duration: 2000
				});
			},
			ToastSuccess(e) {
				uni.showToast({
					title: e,
					icon: 'success',
					duration: 2000
				});
			}
		}
	}
</script>

<style>
	page {
		font-family: Source Han Sans CN;
		background-color: #F8F8F8;
	}

	.all {
		padding: 0 30upx;
	}

	.head {
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin: 30upx 0 18upx 0;
	}

	.head_one {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.head_one_name {
		display: block;
		font-size: 32upx;
		color: #9A9A9A;
	}

	.head_one_name_active {
		color: #343434;
	}

	.head_one_line {
		display: block;
		width: 40upx;
		height: 8upx;
		border-radius: 4upx;
		background-color: #F8F8F8;
		margin-top: 14upx;
	}

	.head_one_line_active {
		background-color: #4688FF;
	}

	.fill {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 25upx;
	}

	.fill_btn {
		font-size: 27upx;
		color: #4788FF;
	}

	.info_must {
		background-color: #FFFFFF;
		border-radius: 20upx;
		padding: 0 30upx;
	}

	.info_must_one {
		height: 110upx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 2upx solid #FFFFFF;
	}

	.info_must_one_title_input {
		display: flex;
		align-items: center;
	}

	.info_must_one_title {
		display: block;
		font-size: 28upx;
		color: #343434;
		width: 120upx;
	}

	.input {
		font-size: 26upx;
		color: #343434;
		width: 450upx;
	}

	.input_phone {
		font-size: 26upx;
		color: #343434;
		width: 400upx;
	}

	.more_icon {
		width: 14upx;
		height: 24upx;
	}

	.pass {
		background-color: #FFFFFF;
		height: 110upx;
		padding: 0 30upx;
		margin-top: 20upx;
		border-radius: 20upx;
	}

	.textarea {
		margin-top: 20upx;
		background-color: #FFFFFF;
		width: 630upx;
		height: 180upx;
		padding: 26upx 30upx;
		font-size: 26upx;
		color: #343434;
		border-radius: 20upx;
		line-height: 1.5;
	}

	.placeholder {
		font-size: 26upx;
		color: #9A9A9A;
		line-height: 1.2;
	}


	.release_btn {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 80upx;
	}

	.btn {
		display: block;
		width: 600upx;
		height: 88upx;
		background-color: #4687FF;
		border-radius: 44upx;
		text-align: center;
		line-height: 88upx;
		font-size: 30upx;
		color: #FFFFFF;
	}

	.phone_btn {
		width: 100upx;
		height: 45upx;
		border-radius: 6upx;
		border: 2upx solid #4687FF;
		line-height: 38upx;
		padding: 0;
		color: #007AFF;
		font-size: 24upx;
		text-align: center;
	}

	.choose_person_num {
		height: 550upx;
		background-color: #FFFFFF;
		border-radius: 20upx 20upx 0 0;
		padding: 30upx;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		align-items: center;
	}

	.choose_person_num_one {
		display: block;
		text-align: center;
		height: 88upx;
		border-bottom: 2upx solid #a1a1a1;
		width: 450upx;
	}
	.share_all{
		position: absolute;
		left: -5000upx;
		
	}
	.share_popup{
		position: relative;
		width: 562upx;
		height: 500upx;
		background-color: #FFFFFF;
		border-radius: 10upx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.success_icon{
		width: 88upx;
		height: 88upx;
	}
	.share_tip{
		display: block;
		width: 290upx;
		font-size: 28upx;
		color: #343434;
		line-height: 50upx;
		text-align: center;
		margin: 40upx 0 50upx 0;
	}
	.share_btn{
		display: block;
		width: 340upx;
		height: 80upx;
		border-radius: 40upx;
		padding: 0;
		font-size: 28upx;
		line-height: 80upx;
	}
	.close_icon{
		position: absolute;
		width: 30upx;
		height: 30upx;
		right: 20upx;
		top: 15upx;
		opacity: 0.68;
	}
</style>
